package com.fastjars.error;

import com.fastjars.core.exception.GlobalExceptionHandler;
import com.fastjars.core.spring.http.Resp;
import org.apache.commons.util.RequestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * AdviceExceptionHandler
 *
 * @author Brant Liu <br> 邮箱：<br>lbf1988@qq.com <br>日期：<br>2018/05/25
 * @version 1.0.0
 */
@ControllerAdvice
public class AdviceExceptionHandler extends GlobalExceptionHandler {
    protected static final Logger LOGGER = LoggerFactory.getLogger(AdviceExceptionHandler.class);

    @ExceptionHandler(value = {Exception.class})
    public ModelAndView defaultException(HttpServletRequest request, HttpServletResponse response, Exception ex) throws IOException {
        return execute(request,response,ex);
    }

    @Override
    public ModelAndView execute(HttpServletRequest request, HttpServletResponse response, Exception ex) throws IOException {
        LOGGER.debug("Request Uri:"+request.getRequestURI());
        LOGGER.debug("Exception:"+ex.getClass().getSimpleName() + ", Detail message:",ex);
        if(RequestUtils.isAjaxRequest(request)){
            return ajaxReqHandler(request, response, ex);
        }
        ModelAndView view = new ModelAndView("error/error");
        view.getModelMap().put("req",request.getRequestURI());
        view.getModelMap().put("exception",ex.getMessage());
        return view;
    }

    public ModelAndView ajaxReqHandler(HttpServletRequest request, HttpServletResponse response, Exception ex) throws IOException {
        responseResult(response,Resp.business().msg(ex.getMessage()).build());
        return null;
    }

    private void responseResult(HttpServletResponse response, Resp resp) throws IOException {
        LOGGER.debug("处理Ajax请求");
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(resp.toJsonString());
        response.getWriter().flush();
        response.getWriter().close();
    }
}
